import { MutableRefObject } from 'react';
import { extendApi } from '@inbiz/utils';
import { IProps } from './index';
import { getTableList } from '../../designer/webServer/services';

export default extendApi(
  (
    _events: MutableRefObject<IProps['callBackEvents']>,
    {
      list,
      optionRef,
      $option,
      props,
      showField,
      getServerData,
      searchField,
      storageField,
      selectData
    }
  ) => {
    return {
      getSaveData: () => {
        const option = optionRef.current || [];

        let propsValue = props.value;
        if (props.childModelConfig) {
          let dataList: any[] = [];
          if (typeof propsValue == 'number') {
            propsValue = String(propsValue);
          }
          if (typeof propsValue == 'string' && propsValue !== '') {
            propsValue = propsValue.split(',');
            propsValue = propsValue.map((item: string) => item.trim());
          }
          if (Array.isArray(propsValue)) {
            dataList = propsValue.map((item: string) => {
              let newOption = [...option];
              let fil = newOption.filter((val: any) => val[storageField] == item);
              return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                pre[next.modelAttr] = fil[0]?.[next.componentAttr];
                pre['_opt'] = 'add';
                return pre;
              }, {});
            });
          }
          const data = {
            value: Array.isArray(propsValue) ? propsValue.join(',') : propsValue,
            childData: props.storageConfig
              ? {
                  controlId: props.controlId,
                  modelKey: props.storageConfig?.business,
                  datas: [
                    ...dataList,
                    {
                      _opt: 'del',
                    },
                  ],
                }
              : undefined,
          };
          return data;
        }
        return {
          value: Array.isArray(propsValue) ? propsValue.join(',') : propsValue,
        };
      },
      loadData: (list: { value: string; label: string }[], isValue: boolean) => {
        $option(list, isValue);
      },
      getData: () => {
        const option = optionRef.current || [];
        let newOption = [...option];
        return newOption;
      },
      getServerData: (params?: any) => {
        return getServerData(params || {});
      },
      getText: () => {
        if (Array.isArray(list)) {
          return list
          .map((item) => {
            return [...selectData, ...(optionRef.current || [])].find((data) => data?.[storageField] === item)?.[showField];
          }) .join(',');
        } else {
          return [...selectData, ...(optionRef.current || [])]?.filter((item: any) => item[storageField] === list)?.[0]?.[showField];
        }
      },
      getSelect: () => {
        if (Array.isArray(list)) {
          return list
          .map((item) => {
            return selectData.find((data) => data?.[storageField] === item);
          });
        } else {
          return selectData?.filter((item: any) => item[storageField] === list)?.[0];
        }
      },
      // 目前只支持设置单个选中，后续根据需求调整
      setValueToLabel: (label: string) => {
        if (!label || label == '' || !label?.length) return;
        let params = {}
        if (props.sourcetype === 'api') {
          params = {
            appId: props.inbiz?.appInfo?.appId || '',
            key: props.sourceModel || '',
            iConditions: {
              pageIndex: 1,
              pageSize: 10,
              label,
            }
          }
        } else {
          const field = [...searchField];
          const conditions = field.map((item, idx) => {
            return {
              index: idx,
              connector: 1,
              condition: [
                {
                  connector: 1,
                  modelName: item.model || '',
                  field: item.field || '',
                  operator: 'like',
                  value: label,
                },
              ],
            }
          });
          params = {
            appId: props.inbiz?.appInfo?.appId || '',
            key: props.sourceModel || '',
            pageInfo: {
              index: 1,
              size: 10,
            },
            conditions,
          }
        }
        return getTableList(params).then(res => {
          if (res?.Rows?.length) {
            let data: {[key: string]: any} | undefined = undefined;
            // 完全匹配查找
            data = res.Rows.find(row => row[props.showconfig?.selectName] === label);
            // 没有完全匹配则进行模糊匹配查找
            if (!data) {
              data = res.Rows.find(row => row[props.showconfig?.selectName].includes(label));
            }
            if (!data) return;
            props.onChange && props.onChange([data[res.primary].toString()]);
            return data;
          }
        })
      }
    };
  },
);
